package com.koalac.ironman.weixin;

import java.util.Set;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

import com.foot.travel.R;
import com.foot.travel.activity.LoginActivity;
import com.foot.travel.activity.MainActivity;
import com.foot.travel.activity.RegisterActivity;
import com.koalac.ironman.cache.CacheHandler;
import com.koalac.ironman.cache.CacheKey;
import com.koalac.ironman.cache.CacheName;
import com.koalac.ironman.cache.SysAppConfig;
import com.koalac.ironman.net.MyRequest;
import com.koalac.ironman.net.ResponseCallback;
import com.koalac.ironman.net.asynchttpclient.AsyncHttpResponseHandler;
import com.koalac.ironman.net.pojo.request.ValidateWeixin;
import com.koalac.ironman.net.pojo.response.Response;
import com.koalac.ironman.net.pojo.response.User;
import com.koalac.ironman.net.pojo.response.WXPersonInfo;
import com.koalac.ironman.util.GBLActivityManager;
import com.koalac.ironman.util.ToastUtil;
import com.koalac.ironman.widget.LoadingDialog;

public class WXLoginHelper {

	Activity mContext;
	public static final int WX_SUCCESS_STATUS = 1;
	LoadingDialog mLoginLoadingDialog;
	
	/**
	 * 获取accesstoken
	 */
	public static final String GET_WX_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?"
			+ "appid=%s"
			+ "&secret=%s"
			+ "&code=%s"
			+ "&grant_type=authorization_code";
	public static final String OPEN_ID = "openid";
	public static final String REFRESH_TOKEN = "refresh_token";
	public static final String ACCESS_TOKEN = "access_token";
	/**
	 *  获取微信的用户信息
	 */
	public  static final String GET_WX_PERSON_INFO_URL = "https://api.weixin.qq.com/sns/userinfo?"
			+ "access_token=%s"
			+ "&openid=%s";
	public static final String ERR_CODE = "errcode";
	public static final String ERR_CODE_VALUE = "40029";
	/**
	 * 刷新access_token有效期
	 */
	public static final String REFRESH_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/refresh_token?"
			+ "appid=%s"
			+ "&grant_type=refresh_token"
			+ "&refresh_token=%s";
	
	

	public WXLoginHelper(Activity activity) {
		mContext = activity;
		mLoginLoadingDialog = LoadingDialog.createLoadingDialog(activity, "", "正在登陆...");
	}

	/**
	 * 获取AccessToken
	 * 
	 * @param wxToken
	 */
	public void getAccessToken(final String wxToken) {
		mLoginLoadingDialog.show();
		/**
		 * 拼接获取accessToken的url
		 */
		String getAccessTokenUrl = String.format(GET_WX_TOKEN_URL,FootTravelWechat.APP_ID,FootTravelWechat.APP_SECRET,wxToken);
		
		MyRequest.getHttpClient().get(getAccessTokenUrl,
				new AsyncHttpResponseHandler() {

					@Override
					public void onProgress(int bytesWritten, int totalSize) {

					}

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							byte[] responseBody) {
						try {
							JSONObject jObject = new JSONObject(new String(
									responseBody));
							
							String openid = jObject.optString(OPEN_ID);
							/**
							 * 若下一步获取用户信息的时候,提示access_token过期
							 * ,就需要用到refresh_token来刷新access_token
							 */
							String refreshToken = jObject
									.optString(REFRESH_TOKEN);
							String accessToken = jObject
									.optString(ACCESS_TOKEN);
							getWXPersonInfo(accessToken, refreshToken, openid);
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							byte[] responseBody, Throwable error) {
						mLoginLoadingDialog.cancel();
						toastFail();
					}

				});

	}
	
	private void toastFail() {
		ToastUtil.toast(mContext, "登陆失败!");
	}

	/**
	 * 获取微信的用户信息
	 * 
	 * @param wxToken
	 * @param refreshToken
	 * @param openid
	 */
	private void getWXPersonInfo(String accessToken, final String refreshToken,
			String openid) {
		String getWXPersonInfoUrl = String.format(GET_WX_PERSON_INFO_URL, accessToken,openid);
		
		MyRequest.getHttpClient().get(getWXPersonInfoUrl,
				new AsyncHttpResponseHandler() {

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							byte[] responseBody) {
						try {
							JSONObject jObject = new JSONObject(new String(
									responseBody));
							if (jObject.optString(ERR_CODE).equals(ERR_CODE_VALUE)) {
								/**
								 * access_token失效
								 */
								refreshToken(refreshToken);
							}
							WXPersonInfo wxPersonInfo = new WXPersonInfo();
							wxPersonInfo.init(jObject);
							weixinLoginKaolaServer(wxPersonInfo);
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onProgress(int bytesWritten, int totalSize) {
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							byte[] responseBody, Throwable error) {
						mLoginLoadingDialog.cancel();
						toastFail();
					}
				});
	}

	/**
	 * 刷新access_token有效期
	 */
	private void refreshToken(final String refreshToken) {
		String refreshTokenUrl = String.format(REFRESH_TOKEN_URL,FootTravelWechat.APP_ID,refreshToken);
		MyRequest.getHttpClient().get(refreshTokenUrl,
				new AsyncHttpResponseHandler() {

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							byte[] responseBody) {
						try {
							JSONObject jObject = new JSONObject(new String(
									responseBody));
							String accessToken = jObject
									.optString(ACCESS_TOKEN);
							String openid = jObject.optString(OPEN_ID);
							getWXPersonInfo(accessToken, refreshToken, openid);
						} catch (JSONException e) {
							e.printStackTrace();
						}

					}

					@Override
					public void onProgress(int bytesWritten, int totalSize) {

					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							byte[] responseBody, Throwable error) {
						mLoginLoadingDialog.cancel();
						toastFail();
					}
				});
	}

	/**
	 * post微信用户信息 登陆考拉服务器
	 * 
	 * @param wxPersonInfo
	 */
	public void weixinLoginKaolaServer(final WXPersonInfo wxPersonInfo) {
		if (!mLoginLoadingDialog.isShowing()) {
			mLoginLoadingDialog.show();
		}
		ValidateWeixin cwxLogin = new ValidateWeixin();

		cwxLogin.setHeadimgurl(wxPersonInfo.getHeadimgurl());
		cwxLogin.setNickname(wxPersonInfo.getNickname());
		cwxLogin.setOpenid(wxPersonInfo.getOpenid());
		cwxLogin.setUnionid(wxPersonInfo.getUnionid());

		MyRequest.request(mContext, cwxLogin, new ResponseCallback() {

			@SuppressLint("UseValueOf")
			@Override
			public void process(boolean result, Context context, Response data,
					String msg) {
				mLoginLoadingDialog.cancel();
				if (result) {
					User user = data.getObject(User.class);
					String token = user.getToken();
					/**
					 * 缓存TOKEN信息
					 */
					SysAppConfig.getInstance().setToken(context, token);
					/**
					 * 缓存用户信息
					 */
					SysAppConfig.getInstance().setUser(context, user);
					/**
					 * 保存输入缓存 微信注册的不保留用户名，返回来的用户名是时间戳
					 */
					CacheHandler.addCacheVal(context, "TOKEN",
							CacheName.INPPUT, CacheKey.INPPUT_LOGIN_USERNAME,
							"");

					((Activity) context).overridePendingTransition(
							R.anim.push_right_in, R.anim.push_right_out);
					Intent intent = new Intent(mContext,MainActivity.class);
					mContext.startActivity(intent);
					GBLActivityManager.getActivityManager().popAllActivityExceptOne(MainActivity.class);
					
				}else {
				    /**
				     * 待填手机号码
				     */
				    if (data.getError().equals("612")) {
					Intent intent = new Intent(context,
						RegisterActivity.class);
					intent.putExtra(RegisterActivity.OPEN_ID, wxPersonInfo.getOpenid());
					intent.putExtra(RegisterActivity.NICK_NAME, wxPersonInfo.getNickname());
					intent.putExtra(RegisterActivity.HEADIMGURL, wxPersonInfo.getHeadimgurl());
					context.startActivity(intent);
					ToastUtil.toast(mContext, "你还没有绑定手机号!");
					GBLActivityManager.getActivityManager().popAllActivityExceptOne(RegisterActivity.class);
				    }else {
					context.startActivity(new Intent(context,
						LoginActivity.class));
//					ToastUtil.toast(mContext, msg);
				    }
				}
			}
		});
	}
}
